package com.situ.hotel.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.hotel.entity.Order;
import com.situ.hotel.entity.User;
import com.situ.hotel.mapper.OrderMapper;
import com.situ.hotel.service.OrderService;
import com.situ.hotel.service.UserService;

@Service
public class OrderServiceImpl implements OrderService{

	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private UserService userService;

	@Override
	public int add(Order order, User user) throws Exception {
		// TODO Auto-generated method stub
		if(order.getUserId()==null) {
			userService.add(user);
			order.setUserId(user.getId());
		}else {
			User oldUser =  userService.getById(order.getUserId());
			if(oldUser==null) {
				throw new Exception("用户信息与系统不匹配");
			}else if(oldUser.getStatus()==1) {
	              throw new Exception("当前用户已被禁用，无法预定房间");			
			}
		}
		return orderMapper.insert(order);
	}

	@Override
	public PageInfo getByPage(Integer page, Integer limit,User user) {
		// TODO Auto-generated method stub
		if(page==null) page=1;
		if(limit==null) limit = 10;
		PageHelper.startPage(page,limit);
		List<Order> list = orderMapper.select(user);
		PageInfo pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	@Override
	public int edit(Order order) {
		// TODO Auto-generated method stub
		return orderMapper.update(order);
	}

	@Override
	public int checkin(Order order) throws Exception {
		// TODO Auto-generated method stub
		if(order.getUser()!=null) {
			
			
		  System.out.println(order.getUsers().size());
		   for (int i=order.getUsers().size()-1;i>=0;i--) {
			   User user = order.getUsers().get(i);
			   if(user.getName()==null && user.getIdcard()==null&&user.getPhone()==null ) {
				   order.getUsers().remove(i);
				   continue;
			   }
			   
			   System.out.println(user+"*************************************************************");
			   System.out.println(user.getStatus()+"******************************************");
			   System.out.println(userService.getById(user.getId())+"***************************");
			   
			   if(user.getId()==null) {
				   userService.add(user);
			   }else {
				   if(userService.getById(user.getId()).getStatus()==1) {
					   throw new Exception(user.getName()+"被禁用");
				   }
			   }
		   }
		   if(order.getUsers().size()==0) {
			   throw new Exception("入住时至少要添加一个用户");
		   }
		}
		
		order.setInTime(new Date());
		order.setStatus(2);
		
		
		return orderMapper.update(order);
	}
}
